//----------------------------------------------------------------
//	NPythonBind Lib
//
//	Convert between Python args and C++ types
//
//	Author: Neil Fang
//	Date:	March,2008
//----------------------------------------------------------------

#pragma once
#include "NException.h"

/*
 *	Conversion template define
*/
template<typename T> 
struct NConversion
{
	/**
	 *	parse the Python args to C++ type
	 *	@param index	index of args
	 *	@param args		the args object, a tuple
	*/
	static T parse(int index, PyObject* args);
	
	/**
	 *	build a Python object form C++ type data
	*/
	static PyObject* build(T);
};

/*
*	Conversion for 'int'
*/
template<>
struct NConversion<int>
{
	static int parse(int index, PyObject* args)
	{
		if(PySequence_Check(args) == 0)
			throw NException("args not provides sequence protocol.");

		if(PySequence_Size(args) <= index)
			throw NException("arg index overflow.");

		PyObject* v = PySequence_GetItem(args, index);
		if(v == NULL)
			throw NException("arg PySequence_GetItem() failed..");
		
		if(!PyNumber_Check(v))
			throw NException("arg type error");

		return PyInt_AsLong(v);
	}

	static PyObject* build(int v)
	{
		return Py_BuildValue("i", v);
	}
};